// 首页导航选项卡 kevinE
// v1.0 2022-2-8 20:22:39
(() => {
	if (public) {
		let cs = $('link');
		let ps = false;
		for (let c of cs) {
			if (~c.href.indexOf('public.css')) ps = true;
		}
		if (!ps) {
			console.warn('未引入公共CSS文件', 'public.css');
			return false;
		}
	} else {
		console.error('未引入公共JS文件', 'public.js');
		return false;
	}

	// 获取配置文件后执行操作
	getConfig('../config/page.json', res => {
		let cfgTabBar = res.golbal.tabBar;
		let path = location.pathname;
		let tabList = cfgTabBar.list
		// 判断当前页面是否存在底部导航选项卡
		let flag = false;
		let data = null;
		for (let i = 0; i < tabList.length; i++) {
			if (~path.indexOf(tabList[i].path)) {
				flag = true;
				data = tabList[i];
				break;
			}
		}
		// 当前页存在底部选项卡
		if (flag) {
			let target = $('.main')[0];
			if (target) {
				let tabBar = createNavBar(cfgTabBar, data);
				tabBar && insertAfter(tabBar, target);
			}
		}
	});

	// 绘制选项卡
	function createNavBar(cfg, self) {
		let path = location.pathname;
		let list = cfg.list;
		let tabBar = document.createElement('div');
		tabBar.className = "first-tab";
		let str = '';
		let relative = getRelative(self);
		for (let i = 0; i < list.length; i++) {
			let data = list[i];
			// 当前页面 匹配 当前数据
			if (~path.indexOf(data.path)) {
				str += '<a>'
					+'<img src="'+data.iconActive+'" />'
					+'<span class="tab-active">'+data.text+'</span>'
				+'</a>';
			}
			// 非激活页面
			else {
				let href = relative + data.path + '.html';
				str += '<a href="'+href+'">'
					+'<img src="'+data.iconDefault+'" />'
					+'<span>'+data.text+'</span>'
				+'</a>';
			}
		}
		tabBar.innerHTML = str;
		return tabBar;
	}
	
	// 获取相对路径
	function getRelative(self) {
		let pn = location.pathname;
		let sp = self.path+'.html';
		return pn.replace(sp, '');
	}
	
	/**
	 * @description 在元素后插入元素
	 * @param {HTMLElement} ne 要被插入的新节点
	 * @param {HTMLElement} te 插入参考目标节点
	 */
	function insertAfter(ne, te) {
		var parent = te.parentNode;
		if (parent.lastChild == te) {
			parent.appendChild(ne);
		} else {
			parent.insertBefore(ne, te.nextSibling);
		}
	}
})();
